<template>
    <div class="flex-col justify-between" style="height: 100%">
        <n-form style="margin-top: 24px" ref="formRef" :model="form" :rules="rules" label-placement="top"
                label-width="120" require-mark-placement="right-hanging">
            <n-form-item label="欢迎语">


                <n-input @mousedown.stop @wheel.stop v-model:value="form.welcomeTip"
                         class="mt-2" type="textarea" placeholder="请输入欢迎语.例如:轻松开始，享受便捷服务,有任何问题？我们随时为您服务。"
                         :autosize="{minRows: 3, maxRows: 6,}" maxlength="300"></n-input>

            </n-form-item>
            <n-form-item label="应用Logo" path="appLogo">
                <jb-avatar v-model:src="form.appLogo"
                           accept="image/jpg,image/png,image/gif,image/bmp,image/jpeg"
                           save-path="logo/{date(yyMMdd)}/{random(6)}/{ori}" :upload="true">

                </jb-avatar>
            </n-form-item>
            <n-form-item label="聊天时,是否展示头像">
                <n-switch v-model:value="form.showAvatar" :round="false">
                    <template #checked>
                        yes
                    </template>
                    <template #unchecked>
                        no
                    </template>
                </n-switch>

            </n-form-item>

            <div v-if="form.showAvatar">
                <n-form-item label="用户头像" path="userAvatar">
                    <jb-avatar v-model:src="form.userAvatar" accept="image/jpg,image/png,image/gif,image/bmp,image/jpeg"
                               save-path="logo/{date(yyMMdd)}/{random(6)}/{ori}" :upload="true">
                    </jb-avatar>

                </n-form-item>
                <n-form-item label="AI头像" path="assistantAvatar">
                    <jb-avatar v-model:src="form.assistantAvatar"
                               accept="image/jpg,image/png,image/gif,image/bmp,image/jpeg"
                               save-path="logo/{date(yyMMdd)}/{random(6)}/{ori}" :upload="true">

                    </jb-avatar>
                </n-form-item>
            </div>

        </n-form>
        <div class="flex justify-center">
            <jb-btn type="primary" @click="handleSubmit">提交-更新UI布局样式配置</jb-btn>
        </div>
    </div>
</template>

<script setup>
import {
    onMounted,
    ref, watch
} from "vue";
import {
    JBoltApi
} from "@/service/request/index.js";
import {
    showSuccessMsg
} from '@/utils/service/msg.js'

// 定义触发的事件
// const emit = defineEmits(['update-success']);

const props = defineProps({
    appId: String
})


const formRef = ref(null)

const rules = {
    userAvatar: {
        required: true,
        message: '请上传用户头像',
        trigger: 'change'
    },
    assistantAvatar: {
        required: true,
        message: '请上传AI头像',
        trigger: 'change'
    },
    appLogo: {
        required: true,
        message: '请上传应用Logo',
        trigger: 'change'
    }

}

const form = ref({
    userAvatar: '',
    assistantAvatar: '',
    appLogo: '',
    showAvatar: false,
    welcomeTip: ''
})

//------监听用户当前是否有更改的数据
const emit = defineEmits(['unSaveData', 'saveData']);
const oldForm = ref({
    userAvatar: '',
    assistantAvatar: '',
    appLogo: '',
    showAvatar: false,
    welcomeTip: ''
})
// 深度比较两个对象
const hasChanges = () => {
    //先比对appLogo 跟showAvatar,welcomeTip,如果不一致返回true,
    // 如果showAvatar是true的话,在比对userAvatar跟assistantAvatar,如果不一致返回true,
    // 如果showAvatar是false的话,就不用比对userAvatar跟assistantAvatar

    return oldForm.value.appLogo !== form.value.appLogo
        || oldForm.value.showAvatar !== form.value.showAvatar
        || oldForm.value.welcomeTip !== form.value.welcomeTip||
        (form.value.showAvatar && (oldForm.value.userAvatar !== form.value.userAvatar || oldForm.value.assistantAvatar
            !== form.value.assistantAvatar))
};
//监听表单的值变化
watch(() => form.value, (newValue, oldValue) => {
    if (hasChanges() == false) {
        emit('saveData')
    } else {
        emit('unSaveData')
    }


}, {deep: true})

//------监听用户当前是否有更改的数据


async function handleSubmit(fun) {
    await formRef.value?.validate()
    console.log('提交表单', JSON.stringify(form.value))
    let url = '/aiAppConfig/updateConfigByKey';
    await JBoltApi.post(url, {
        linkType: 'app',
        linkId: props.appId,
        configKey: 'uiConfig',
        configValue: JSON.stringify(form.value)
    }).then(res => {
        showSuccessMsg('保存成功,请刷新页面更新右侧聊天界面新头像');
        emit('saveData');
        oldForm.value = {...form.value};//更新以后,要保证两个对象中的值一致

    });
}

// let isEdit = ref(false)

function loadConfigData() {
    JBoltApi.tryGet(`/aiAppConfig/getConfigByCondition`, {
        linkType: "app",
        linkId: props.appId,
        configKey: 'uiConfig'
    }).then(res => {
        if (res.data !== null) {
            //判断res.data中是否含有welcomeTip
            if (!res.data.hasOwnProperty('welcomeTip')) {
                form.value = {...res.data, welcomeTip: ""};
                oldForm.value = {...res.data, welcomeTip: ""};
            } else {
                form.value = {...res.data};
                oldForm.value = {...res.data};
            }
            console.debug('form.value', form.value)
            console.debug('oldForm.value', oldForm.value)

        }
    }).catch((error) => {
        console.error(error)
    })


}

onMounted(() => {
    if (props.appId) {
        loadConfigData()
    }
})
</script>


<style scoped>

</style>